package cz.muni.fi.pb138.bookinfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class Launcher extends Activity {
	protected static final int ACTIVITY_SELECT_IMAGE = 0;
	private Button ok;
	private Button info;
	private Button review;
	private Button availability;
	private Button help;
	private Button authors;
	private Button expl;
	private Button path;
	private Button camera;
	private static String pathToImg;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.launcher);
		
		expl = (Button) findViewById(R.id.explorer);
		ok = (Button) findViewById(R.id.ok);
		info = (Button) findViewById(R.id.info);
		review = (Button) findViewById(R.id.review);
		availability = (Button) findViewById(R.id.availability);
		help = (Button) findViewById(R.id.help);
		authors = (Button) findViewById(R.id.authors);
		path = (Button) findViewById(R.id.path);
		camera = (Button) findViewById(R.id.camera);
		
		if(pathToImg == null || pathToImg.isEmpty()) {
			path.setEnabled(false);
		}

		if(!isConnected(this)) {
			new AlertDialog.Builder(Launcher.this).setTitle(R.string.noconnection)
			
			.setMessage(R.string.noconnalert)
			.setPositiveButton("OK", null).show();
		}
		
		expl.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(Launcher.this, FileDialog.class));
			}
		});
		
		ok.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {				
				if(pathToImg != null && !pathToImg.isEmpty() /*&& isConnected(this)*/) {
					//jen pro kontrolu, jestli funguje
					new AlertDialog.Builder(Launcher.this).setTitle(scanImage())
					
					.setPositiveButton("OK", null).show();
					
					//zde se bude resit i samotne parsovani a ziskavani dat z databaze (asi?)
					if(scanImage() != null) {
						info.setEnabled(true);
						review.setEnabled(true);
						availability.setEnabled(true);
					}
				} 
				
				if(pathToImg == null || pathToImg.isEmpty()) {
					new AlertDialog.Builder(Launcher.this).setTitle(R.string.nopath)
					
					.setMessage(R.string.nopathalert)
					.setPositiveButton("OK", null).show();
				}
				
				/*if(!isConnected(this)) {
					new AlertDialog.Builder(Launcher.this).setTitle(R.string.noconnection)
					.setMessage(R.string.noconnalert)
					.setPositiveButton("OK", null).show();
				}*/
			}
		});

		info.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(Launcher.this, Info.class));
			}
		});

		review.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(Launcher.this, Review.class));
			}
		});

		availability.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(Launcher.this, Availability.class));
			}
		});
		
		help.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(Launcher.this, Help.class));
			}
		});

		authors.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(!isConnected(this)) {
					new AlertDialog.Builder(Launcher.this).setTitle(R.string.noconnection)
					
					.setMessage(R.string.noconnalert)
					.setPositiveButton("OK", null).show();
				} else {
					startActivity(new Intent(Launcher.this, Authors.class));
				}
			}
		});

		path.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(pathToImg != null && !pathToImg.isEmpty()) {					
					Toast.makeText(Launcher.this, pathToImg, 3000).show();
				} 
			}
		});
		
		camera.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {	//lze nejak dostat hned cestu k fotce ?		
				if (hasCamera()) {
					//startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), 0);
				
					Intent i = new Intent(Intent.ACTION_PICK,
				             android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(i, ACTIVITY_SELECT_IMAGE); 
					
					
					
				} else {
					new AlertDialog.Builder(Launcher.this).setTitle(R.string.nocamera)
					
					.setMessage(R.string.nocamalert)
					.setPositiveButton("OK", null).show();
				}
			}			
		});
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
	    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

	    switch(requestCode) { 
	    case ACTIVITY_SELECT_IMAGE:
	        if(resultCode == RESULT_OK){  
	            Uri selectedImage = imageReturnedIntent.getData();
	            String[] filePathColumn = {MediaStore.Images.Media.DATA};

	            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
	            cursor.moveToFirst();

	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            String filePath = cursor.getString(columnIndex);
	            cursor.close();
	            
	            pathToImg = filePath;

	        }
	    }
	}

	public void onResume() {
		super.onResume();
		
		if(pathToImg != null && !pathToImg.isEmpty()) {
			path.setEnabled(true);
		}
	}
	
	private static boolean isConnected(Context context) {
	    ConnectivityManager connectivityManager = (ConnectivityManager)
	        context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo networkInfo = null;
	    if (connectivityManager != null) {
	        networkInfo =
	            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
	    }
	    return networkInfo == null ? false : networkInfo.isConnected();
	}
	
	protected boolean isConnected(OnClickListener onClickListener) {
		return isConnected(this);
	}
	
	public void setPathToImg(String path) {	
		pathToImg = path;
	}

	public boolean hasCamera() {
		if(this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			return true;
		}
		return false;
	}
	
	public String scanImage() {	
		try {
			BarcodeScanner scanner = new BarcodeScanner();
			String isbn = scanner.decode(pathToImg);
			return isbn;
		} catch(Exception e) {
			new AlertDialog.Builder(Launcher.this).setTitle(R.string.scanerr)
			
			.setMessage("During scanning the picture occured this error: "+ e)
			.setPositiveButton("OK", null).show();
			return null;
		}	
	}
}